<template>
  <div class="container margin-lr">
    <use-navbar title="个人资料"></use-navbar>

    <div class="border-radius dflex-b bg-main padding-lr padding-tb-sm margin-top" @click="toHeadimg">
      <span>头像</span>

      <div class="dflex-c">
        <img class="border-radius-c headimg image-60 margin-right-xs"
          :src="member.member_headimg || '/static/images/user/default.png'">
        <div class="iconfont iconjiantou-01 fs-sm" style="color: #c0c0c0;"></div>
      </div>
    </div>

    <div class="border-radius margin-top-sm">
      <use-list-title title="昵称" iconfont=" " @goto="toEdit('nickname', '昵称', 26)"
        :tip="member.member_nickname"></use-list-title>
      <use-list-title title="性别" iconfont=" " @goto="toSex"
        :tip="(member.member_gender == 0 ? '未知' : member.member_gender == 1 ? '男' : '女') || '未知'">
      </use-list-title>
      <use-list-title title="地区" iconfont=" " @goto="toCity" :tip="member.member_city"></use-list-title>
    </div>

    <div class="border-radius margin-top-sm">
      <use-list-title title="姓名" iconfont=" " @goto="toEdit('truename', '姓名', 10)"
        :tip="member.member_truename || '未实名'"></use-list-title>
    </div>

    <div class="border-radius margin-top-sm">
      <use-list-title title="个人签名" iconfont=" " @goto="toEdit('slogan', '个人签名', 30)"
        :tip="member.slogan || '未填写'"></use-list-title>
    </div>

    <div class="padding"></div>

    <l-clipper v-if="clipperShow" :image-url="member.member_headimg" :quality="0.6" @success="clipperSuccess"
      @cancel="clipperShow = false"></l-clipper>

    <use-popup v-model="editShow" bgclass=" " mode="top" borderRadius="20">
      <div class="oper-area border-radius bg-main pos-r">
        <div class="pos-a pos-top pos-right padding-sm" @click="editShow = false">
          <div class="iconfont iconguanbi"></div>
        </div>

        <div class="dflex-b ft-dark fs-xs margin-bottom-sm margin-lr-xs">
          <div>修改{{ editTxt }}</div>
          <div>{{ editVal.length }}/{{ editMaxLength }}</div>
        </div>
        <div class="dflex border-radius-sm field" style="padding: 18rpx 16rpx">
          <textarea class="fwb fs-sm" type="text"
            v-model="editVal" auto-height disable-default-padding
            style="max-height: 160rpx; min-height: 40rpx; height: 40rpx; font: initial;"
            :focus="editShow" confirm-type="done"
            :show-confirm-bar="false" cursor-spacing="20" placeholder="请输入" placeholder-class="fs-sm"
            :maxlength="editMaxLength" @confirm="editConfirm" />
        </div>

        <div class="bg-base margin-top-xl tac w-full border-radius-lg padding-tb-sm" @click.stop="editConfirm">
          提交
        </div>
      </div>
    </use-popup>

    <use-action-sheet v-model="actionSheetShow" :list="actionSheetList" :tips="actionSheetTips"
      @click="actionSheetClick"></use-action-sheet>

    <use-address ref="useAddress" @onConfirm="changeAddr" cancelColor="#bbb" themeColor="#ff6a6c"></use-address>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import lClipper from '@/sub-user/components/lime-clipper/components/l-clipper/l-clipper';

const store = useStore();
const member = computed(() => store.state.member); // 使用 vuex 获取 state

const clipperShow = ref(false);
const editShow = ref(false);
const editKey = ref('');
const editVal = ref('');
const editTxt = ref('');
const editMaxLength = ref(30);

const actionSheetShow = ref(false);
const actionSheetList = ref([{ text: "男", color: "#333" }, { text: "女", color: "#333" }]);
const actionSheetTips = ref({ text: "", color: "#9a9a9a", size: 24 });

// 其他方法...
const toHeadimg = () => {
  clipperShow.value = true;
};

const clipperSuccess = async (e) => {
  let url = e.url;
  uni.showLoading({ title: '上传中' });
  // #ifdef H5
  url = URL.createObjectURL(await base64ToBlob({ b64data: url }));
  // #endif

  const uRes = await proxy.$api.uploadFile(url, `${Date.now()}.png`).catch(err => {
    proxy.$api.msg(err.message);
    uni.hideLoading();
  });

  updateUser({ avatar: uRes.url }, () => {
    member.value.member_headimg = uRes.url;
    clipperShow.value = false;
    uni.hideLoading();
  });

  try {
    URL.revokeObjectURL(url);
  } catch {}
};

// #ifdef H5
const base64ToBlob = ({ b64data = '', contentType = 'image/png' } = {}) => {
  return new Promise((resolve, reject) => {
    try {
      const arr = b64data.split(',');
      const bytes = window.atob(arr[1]);
      const ua = new Uint8Array(new ArrayBuffer(bytes.length));
      for (let i = 0; i < bytes.length; i++) {
        ua[i] = bytes.charCodeAt(i);
      }

      resolve(new Blob([ua], { type: contentType }));
    } catch (e) {
      reject(e);
    }
  });
};
// #endif

const toEdit = (key, txt, len) => {
  editShow.value = true;
  editKey.value = key;
  editTxt.value = txt;
  editMaxLength.value = len;
};

const editConfirm = () => {
  let data = {};
  data[editKey.value] = editVal.value.replace(/\n/g, '').replace(/\r\n/g, '').trim();
  if (!data[editKey.value]) {
    proxy.$api.msg('请填写' + editTxt.value);
    return;
  }
  updateUser(data, () => {
    if (editKey.value == 'nickname') {
      member.value['member_nickname'] = data[editKey.value];
    } else if (editKey.value == 'truename') {
      member.value['member_truename'] = data[editKey.value];
    } else {
      member.value[editKey.value] = data[editKey.value];
    }
    editShow.value = false;
    editVal.value = '';
  });
};

const toSex = () => {
  actionSheetShow.value = true;
};

// 点击操作菜单
const actionSheetClick = (index) => {
  if (member.value.member_gender == index + 1) return;

  updateUser({ gender: index + 1 }, () => {
    member.value.member_gender = index + 1;
  });
};

const toCity = () => {
  useAddress.value.open();
};

const changeAddr = (res) => {
  if (member.value.member_city == res.label) return;
  updateUser({ comment: res.label }, () => {
    member.value.member_city = res.label;
  });
};

const updateUser = (data, callback) => {
  proxy.$func.usemall.call('member/updateUser', data).then(res => {
    if (res.code == 200) {
      if (typeof callback === 'function') {
        callback(res);
        store.commit('putMember', member.value); // 更新 Vuex 状态
      }
      return;
    }

    proxy.$api.msg(res.msg);
  });
};
</script>

<style lang='scss'>
.page {
  background: $page-color-base;
}

.oper-area {
  width: 80vw;
  padding: 80rpx;
  padding-top: 100rpx;
  margin-top: 20vh;
  margin-left: 10vw;

  .field {
    background-color: #f5f5f5;
  }
}
</style>
